package com.product.shop.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.product.shop.service.GoodsService;
import com.product.shop.vo.GoodsVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.product.shop.entity.OrderInfoEntity;
import com.product.shop.service.OrderInfoService;
import com.product.common.utils.PageUtils;
import com.product.common.utils.R;



/**
 * 
 *
 * @author brh
 * @email sunlightcs@gmail.com
 * @date 2022-02-22 16:30:11
 */
@RestController
@RequestMapping("shop/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate StringredisTemplate;
    @Autowired
    private RedissonClient redissonClient;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderInfoEntity orderInfo = orderInfoService.getById(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.save(orderInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    //订单生成
    @RequestMapping("/createOrder")
    public R createOrder(@RequestBody GoodsVo goodsVo,@RequestParam("path") String Path){
        String path = StringredisTemplate.opsForValue().get(goodsVo.getGoodsId().toString());
        if (path.equals(Path)){
            OrderInfoEntity order = new OrderInfoEntity();
            //获取锁
            RLock lock = redissonClient.getLock("lock");
            try{
                //加锁
                lock.lock();
                //获取用户是否买过该商品
                Object goodId = redisTemplate.boundHashOps(goodsVo.getUserId()).get("goodId");
                //获取该商品在redis中的库存
                Integer stockCount = (Integer) redisTemplate.boundHashOps(goodsVo.getGoodsId()).get("StockCount");
                if (goodId==null){//没有买过
                    if (stockCount > 0 || stockCount > goodsVo.getGoodsStock()){//库存不为0 且 库存大于购买数量
                        System.out.println("购买成功");
                        //创建订单
                        //首先创建UUID
                        UUID uuid = UUID.randomUUID();
                        String str = uuid.toString();
                        String id = str.replace("-", "");
                        order.setOrderId(id);
                        order.setUserId(goodsVo.getUserId());
                        order.setGoodsId(goodsVo.getGoodsId());
                        order.setGoodsName(goodsVo.getGoodsName());
                        order.setGoodsCount(1);
                        order.setGoodsPrice(goodsVo.getMiaoshaPrice());
                        order.setGoodsChannel(1);
                        order.setStatus(0);
                        order.setCreateDate(new Date());
                        orderInfoService.save(order);
                        //redis库存-1
                        redisTemplate.boundHashOps(goodsVo.getGoodsId()).put("StockCount",stockCount-1);
                        //将用户购买的商品数量存入redis中
                        redisTemplate.boundHashOps(goodsVo.getUserId()).put("goodsStock",order.getGoodsCount());
                        return R.ok();
                    }else{
                        //库存不足,购买失败0
                        System.out.println("购买失败");
                        return R.error("库存不足,请早点来");
                    }

                }else{//买过了
                    System.out.println("买过了,别买了");
                    return R.error("您已秒杀过此商品");
                }
            }finally {
                //释放锁
                lock.unlock();
            }
        }else{
            return R.error("地址不对,快滚!");
        }
    }

    //我的订单
    @RequestMapping("/myOrder/{id}")
    public R myOrder(@PathVariable("id") Long id){
        List<OrderInfoEntity> orderInfo = orderInfoService.myOrder(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    //隐藏接口
    @RequestMapping("/MiaoShaPath/{gid}")
    public R MiaoShaPath(@PathVariable("gid") Integer gid){
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String path = str.replace(gid+"-", "");
        System.out.println(path);
        StringredisTemplate.opsForValue().set(gid.toString(),path,30, TimeUnit.SECONDS);
        return R.ok().put("path",path);
    }

}
